package com.dadaguai.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dadaguai.common.BusinessException;
import com.dadaguai.common.R;
import com.dadaguai.config.AppConfig;
import com.dadaguai.constants.CaptchaConstants;
import com.dadaguai.constants.ResponseCode;
import com.dadaguai.domain.EmailCode;
import com.dadaguai.domain.UserInfo;
import com.dadaguai.mapper.UserInfoMapper;
import com.dadaguai.service.EmailCodeService;
import com.dadaguai.mapper.EmailCodeMapper;
import com.dadaguai.utils.Tools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.mail.internet.MimeMessage;
import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * @author 王半仙
 * @description 针对表【email_code(邮箱验证码)】的数据库操作Service实现
 * @createDate 2023-10-20 11:28:40
 */
@Service
public class EmailCodeServiceImpl extends ServiceImpl<EmailCodeMapper, EmailCode>
        implements EmailCodeService {

    @Resource
    UserInfoMapper userInfoMapper;
    @Resource
    EmailCodeMapper emailCodeMapper;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Resource
    JavaMailSender javaMailSender;

    @Resource
    AppConfig appConfig;
    /**
     * 记录日志
     */
    private static final Logger logger = LoggerFactory.getLogger(EmailCodeServiceImpl.class);

    /**
     * 发送验证码
     * @param email
     * @param type 0-注册；1-修改密码
     * @return
     * @throws BusinessException
     */
    @Transactional
    @Override
    public Boolean sendEmailCode(String email,Integer type) throws BusinessException {
        //type = 1 修改密码，查询邮箱是否注册
        if (type.equals(CaptchaConstants.TYPE_CHANGE_PASSWORD)){
            Integer count = queryEmailRegister(email);
            if (count == 0) {
                return false;
            }
        }
        String code = Tools.createCode(1);
        // 将验证码保存到redis
        redisTemplate.opsForValue().set(CaptchaConstants.EMAIL_CODE_KEY + email, code, 5, TimeUnit.MINUTES);
        handleSendEmailCode(email, code);
        return true;
    }

    /**
     * 验证码校验
     *
     * @param code
     * @param type 0=图片验证码；1=邮箱验证码
     * @param email
     * @return
     */
    @Override
    public R checkCode(String code, Integer type, String email) {
        if (type == 0) {
            String key = CaptchaConstants.IMG_CODE_KEY + email;
            String s = redisTemplate.opsForValue().get(key);
            if (Tools.isEmpty(s) || !s.equals(code)) {
                return R.error("验证码错误",ResponseCode.USER_PARAM_ERROR);
            }
            redisTemplate.delete(key);
            return R.success("验证码正确");
        } else {
            String key = CaptchaConstants.EMAIL_CODE_KEY + email;
            String s = redisTemplate.opsForValue().get(key);
            if (Tools.isEmpty(s) || !s.equals(code)) {
                return R.error("验证码错误",ResponseCode.USER_PARAM_ERROR);
            }
            redisTemplate.delete(key);
            return R.success("验证码正确");
        }
    }

    /**
     * 查询email是被注册
     *
     * @param email
     * @return
     */
    public Integer queryEmailRegister(String email) {
        LambdaQueryWrapper<UserInfo> queryWrapper = Wrappers.lambdaQuery();
        queryWrapper.eq(!Tools.isEmpty(email), UserInfo::getEmail, email);
        return userInfoMapper.selectCount(queryWrapper);
    }

    /**
     * 发送邮件
     *
     * @param email 收件人地址
     * @param code  邮箱验证码
     * @throws BusinessException
     */
    public void handleSendEmailCode(String email, String code) throws BusinessException {
        try {
            MimeMessage mimeMessage = javaMailSender.createMimeMessage();
            MimeMessageHelper helper = new MimeMessageHelper(mimeMessage, true);
            helper.setFrom(appConfig.getSendEmailUsername()); // 邮件发送地址
            helper.setTo(email); //收件人地址
            helper.setSubject("大大怪论坛的邮箱验证码"); // 邮件标题

            helper.setText("验证码为: " + code+ " 十分钟内有效");

            helper.setSentDate(new Date()); // 邮件日期
            javaMailSender.send(mimeMessage); // 发送邮件
        } catch (Exception e) {
            logger.error("邮件发送失败，请检查您的邮箱是否正确", e);
            throw new BusinessException("邮件发送失败，请检查您的邮箱是否正确", ResponseCode.EMAIL_SEND_ERROR);
        }

    }

}




